package com.stx.mall.dao.impl;

import com.stx.mall.dao.UserDAO;
import com.stx.mall.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(User user) {
        String sql = "insert into t_cm_user values (seq_cm_user.nextval, ?, ?, 1, ?, sysdate)";

        jdbcTemplate.update(sql, user.getUsername(),
                                    user.getPassword(), user.getTel());

        System.out.println(user.getUsername() + "新增成功！");
    }

    @Override
    public User findByName(String username) {
        String sql = "select * from t_cm_user where username = ?";
        List<User> userList
                = jdbcTemplate.query(sql, new UserRowMapper(), username);
        return userList.isEmpty() ? null : userList.get(0);
    }

    @Override
    public List<User> findAll() {
        String sql = "select * from t_cm_user order by createTime desc";
        List<User> userList = jdbcTemplate.query(sql, new UserRowMapper() );
        return userList;
    }

    class UserRowMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            //映射每一列数据到一个User对象上
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            user.setSex(resultSet.getInt("sex"));
            user.setTel(resultSet.getString("tel"));
            return user;
        }
    }


}
